//
// Author: Vladimir Migashko <migashko@gmail.com>, (C) 2011
//
// Copyright: See COPYING file that comes with this distribution
//

#ifndef FASYS_FASYS_CONFIG_SPACES_HPP
#define FASYS_FASYS_CONFIG_SPACES_HPP

#include "types.hpp"
#include "channel_space.hpp"
#include <list>
#include <stdexcept>
namespace fasys{

class config_spaces
{
  typedef std::list<channel_space> space_list;
public:

  void add( const channel_space& cs )
  {
    space_list::iterator itr = _find_space(cs.channel);
    if ( itr != _spaces.end() )
      _spaces.erase(itr);

    // ищем место куда вставлять
    itr = _find(cs.channel);
    if ( itr == _spaces.end() )
      _spaces.push_back(cs);
    else
      _spaces.insert(itr, cs); // < вставляем перед найденным элементом, чтобы экранировать его (test.my. вставиться перед test.)
  }

  const channel_space& find(const std::string& channel) const
  {
    space_list::const_iterator itr = _find(channel);
    if ( itr != _spaces.end() )
        return *itr;
    return _empty;
    /*
    space_list::const_iterator itr = _spaces.begin();
    for ( ;itr!=_spaces.end(); ++itr )
    {
      if ( 0 == channel.compare(0, itr->channel.size(), itr->channel) )
        return *itr;
    }
    return _empty;
    */
  }

  const channel_space& find_space(const std::string& channel) const
  {
    space_list::const_iterator itr = _find_space(channel);
    if ( itr != _spaces.end() )
        return *itr;
    return _empty;
  }

  /*
  const channel_space& find(const std::string& channel) const
  {
    space_map::const_iterator itr = _spaces.lower_bound( channel );
    if ( itr == _spaces.end() )
      return _empty;
    return itr->second;
  }*/

private:
  space_list::const_iterator _find_space(const std::string& channel) const
  {
    space_list::const_iterator itr = _spaces.begin();
    for ( ;itr!=_spaces.end(); ++itr )
    {
      if ( itr->channel == channel )
        return itr;
    }
    return _spaces.end();
  }

  space_list::iterator _find_space(const std::string& channel)
  {
    space_list::iterator itr = _spaces.begin();
    for ( ;itr!=_spaces.end(); ++itr )
    {
      if ( itr->channel == channel )
        return itr;
    }
    return _spaces.end();
  }

  space_list::const_iterator _find(const std::string& channel) const
  {
    space_list::const_iterator itr = _spaces.begin();
    for ( ;itr!=_spaces.end(); ++itr )
    {
      if ( 0 == channel.compare(0, itr->channel.size(), itr->channel) )
        return itr;
    }
    return _spaces.end();
  }

  space_list::iterator _find(const std::string& channel)
  {
    space_list::iterator itr = _spaces.begin();
    for ( ;itr!=_spaces.end(); ++itr )
    {
      if ( 0 == channel.compare(0, itr->channel.size(), itr->channel) )
        return itr;
    }
    return _spaces.end();
  }


  channel_space _empty;
  space_list _spaces;
};

}

#endif

